#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <fcntl.h>

#define PORT 8080
#define BUFFER_SIZE 1024
#define ROOT_DIR "./www"  // 静态文件根目录

// 发送HTTP响应头
void send_http_header(int client_socket, int status_code, const char *content_type, long content_length) {
    char header[BUFFER_SIZE];
    
    // 根据状态码设置状态信息
    const char *status_message;
    if (status_code == 200) {
        status_message = "OK";
    } else if (status_code == 404) {
        status_message = "Not Found";
    } else if (status_code == 500) {
        status_message = "Internal Server Error";
    } else {
        status_message = "Unknown";
    }
    
    // 构建HTTP响应头
    sprintf(header, "HTTP/1.1 %d %s\r\n", status_code, status_message);
    sprintf(header + strlen(header), "Content-Type: %s\r\n", content_type);
    sprintf(header + strlen(header), "Content-Length: %ld\r\n", content_length);
    sprintf(header + strlen(header), "Connection: close\r\n");
    sprintf(header + strlen(header), "\r\n");
    
    // 发送响应头
    send(client_socket, header, strlen(header), 0);
}

// 获取文件的MIME类型
const char *get_mime_type(const char *filename) {
    const char *ext = strrchr(filename, '.');
    if (!ext) return "application/octet-stream";
    
    if (strcmp(ext, ".html") == 0 || strcmp(ext, ".htm") == 0) return "text/html";
    if (strcmp(ext, ".css") == 0) return "text/css";
    if (strcmp(ext, ".js") == 0) return "application/javascript";
    if (strcmp(ext, ".jpg") == 0 || strcmp(ext, ".jpeg") == 0) return "image/jpeg";
    if (strcmp(ext, ".png") == 0) return "image/png";
    if (strcmp(ext, ".gif") == 0) return "image/gif";
    if (strcmp(ext, ".pdf") == 0) return "application/pdf";
    
    return "application/octet-stream";
}

// 处理客户端请求
void handle_client(int client_socket) {
    char request[BUFFER_SIZE] = {0};
    char filename[BUFFER_SIZE] = {0};
    char method[BUFFER_SIZE] = {0};
    char path[BUFFER_SIZE] = {0};
    
    // 读取HTTP请求
    ssize_t bytes_received = recv(client_socket, request, BUFFER_SIZE - 1, 0);
    if (bytes_received <= 0) {
        close(client_socket);
        return;
    }
    
    // 解析HTTP请求行
    sscanf(request, "%s %s", method, path);
    
    // 仅处理GET请求
    if (strcmp(method, "GET") != 0) {
        send_http_header(client_socket, 501, "text/html", 0);
        close(client_socket);
        return;
    }
    
    // 构建文件路径
    if (strcmp(path, "/") == 0) {
        strcpy(path, "/index.html");
    }
    sprintf(filename, "%s%s", ROOT_DIR, path);
    
    // 检查文件是否存在
    struct stat file_stat;
    if (stat(filename, &file_stat) < 0) {
        // 文件不存在，返回404错误
        const char *not_found_content = "<h1>404 Not Found</h1>";
        send_http_header(client_socket, 404, "text/html", strlen(not_found_content));
        send(client_socket, not_found_content, strlen(not_found_content), 0);
        close(client_socket);
        return;
    }
    
    // 打开文件
    int file_fd = open(filename, O_RDONLY);
    if (file_fd < 0) {
        // 无法打开文件，返回500错误
        const char *server_error_content = "<h1>500 Internal Server Error</h1>";
        send_http_header(client_socket, 500, "text/html", strlen(server_error_content));
        send(client_socket, server_error_content, strlen(server_error_content), 0);
        close(client_socket);
        return;
    }
    
    // 获取文件的MIME类型
    const char *mime_type = get_mime_type(filename);
    
    // 发送HTTP响应头
    send_http_header(client_socket, 200, mime_type, file_stat.st_size);
    
    // 发送文件内容
    char buffer[BUFFER_SIZE];
    ssize_t bytes_read;
    while ((bytes_read = read(file_fd, buffer, BUFFER_SIZE)) > 0) {
        send(client_socket, buffer, bytes_read, 0);
    }
    
    // 关闭文件和客户端连接
    close(file_fd);
    close(client_socket);
}

int main() {
    int server_socket, client_socket;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
    
    // 创建套接字
    server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }
    
    // 设置套接字选项
    int opt = 1;
    if (setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }
    
    // 配置服务器地址
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(PORT);
    
    // 绑定套接字
    if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }
    
    // 监听连接
    if (listen(server_socket, 5) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }
    
    printf("Server listening on port %d...\n", PORT);
    
    // 主循环处理客户端连接
    while (1) {
        // 接受客户端连接
        client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_len);
        if (client_socket < 0) {
            perror("accept");
            continue;
        }
        
        // 处理客户端请求
        handle_client(client_socket);
    }
    
    // 关闭服务器套接字
    close(server_socket);
    return 0;
}    